C - passing a pointer to a function

chris (2008-10-30 20:50:52)
1919 views
0 replies
The purpose of this short program is to illustrate the concet of passing a pointer to a function in C. I was prompted to write this example by somebody on the devshed c programming forum asking for a solution to a problem. This is the first stage of understanding how these mechanisms work in C.

This is known as call-by-reference, because instead of passing a copy of a value to a function, I pass a pointer to that value instead, which means it can be accessed and modified by other functions.

Anyway, here is a very simple pass by reference in action:

#include <stdio.h>
#include <string.h>

char func(char *string);

int main(int argc, char* argv[]){
	char* string;

	string = "hello world";
	func(string);

	return 0;
}

char func(char* str){
	printf("\nThe string came in as %s \n",str);
	return 1;
}


of course if you compile and run this program, the output is as follows:

secondhalf-lm:junk clacy$ ./foo 

The string came in as hello world 
secondhalf-lm:junk clacy$ 


christo
comment